package com.welse.modulebiz.controller;

import com.welse.modulebiz.domain.Result;
import com.welse.modulebiz.domain.dto.EmailLoginDto;
import com.welse.modulebiz.domain.dto.Login;
import com.welse.modulebiz.domain.dto.PhoneLoginDto;
import com.welse.modulebiz.domain.dto.RedisTransKey;
import com.welse.modulebiz.domain.entity.Member;
import com.welse.modulebiz.service.MemberService;
import com.welse.modulebiz.utils.DateUtil;
import com.welse.modulebiz.utils.IpAddressUtil;
import com.welse.modulebiz.utils.JwtUtil;
import com.welse.modulebiz.utils.Md5Util;
import jakarta.servlet.http.HttpServletRequest;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.concurrent.TimeUnit;

@RequestMapping("/user/login")
@RestController
public class UserLoginController {

    @Autowired
    private MemberService memberService;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private HttpServletRequest request;

    @PostMapping("/username")
    public Result login(Login login) {
        // 检查用户名或者邮箱是否存在
        Member member = memberService.findByUserid(login.getUsername());
        if (member == null) {
            return Result.error("用户不存在");
        } else {
            if (member.getPwd().equals(Md5Util.getMD5String(login.getPassword()))) {
                // 登录成功
                member.setLoginip(IpAddressUtil.getIpAddress(request));
                member.setLogintime(DateUtil.getCurrentDate());
                memberService.findByUserid(member.getUserid());
                memberService.updateById(member);
                //生成token
                Map<String, Object> claims = new HashMap();
                claims.put("token", member.getMid());
                claims.put("userid", member.getUserid());
                String token = JwtUtil.generateToken(claims);

                stringRedisTemplate.opsForValue().set(RedisTransKey.getTokenKey(member.getUserid()), token, 60 * 24 * 30, TimeUnit.MINUTES);
                return Result.success(token);
            }
            else {
                return Result.error("密码错误");
            }
        }
    }

    @PostMapping("/email")
    public Result login(EmailLoginDto emailLoginDto) {
        return Result.error("暂不支持邮箱登录");
    }

    @PostMapping("/phone")
    public Result login(PhoneLoginDto phoneLoginDto) {
        return Result.success();
    }
}
